app_family.controller("controller_addmessage", function($scope, $rootScope, httpRequest, $location) {
	$rootScope.$broadcast('currentModule', 'controller_addmessage'); // 标记当前属于哪个模块
	$rootScope.$broadcast('footerFlag', false); // 是否显示底部导航
	$scope.imagebasepath = imagebasepath;
	$scope.msgCont = '';
	$scope.familyInfo = {};
	
	data_sessionStorage = JSON.parse(sessionStorage.getItem('data_sessionStorage'));
	
	var push_touser = "";
	var olderlist = "";
    var push_card = "";
    var push_phone = "";
    var push_name = "";
    $scope.obj = new Object();
    $scope.msgList = []; // 消息列表
    $scope.type_chat = data_sessionStorage.chat.chatType; // 聊天模式
	
	/**
	 * 获取列表 若未绑定，跳往绑定页面
	 */
    if (data_sessionStorage.chat.chatType === 'single') { // 单独发给一位
    	$('a#returnBack').attr('href', '#/olderinfo');
    	
		var data = [];
		// 家属基本信息
		$scope.familyInfo = {
			icon : data_sessionStorage.familyInfo.icon,
			userName : data_sessionStorage.familyInfo.name,
			sex : data_sessionStorage.familyInfo.sex
		};
		
		$scope.familyList =[];
		$scope.familyList.push(data.obj);
		push_touser += "_" + data.obj.account + "_";
        push_phone += "_" + data.obj.mobile + "_";
        push_name += "_" + data.obj.user_name + "_";
        push_card += "_" + data.obj.id_card_no + "_";
        
        olderlist += data.obj.account; // 获取互动记录的账号
        
        $scope.getChatRecord(data_sessionStorage.familyInfo.phone, olderlist);
    } else if (data_sessionStorage.chat.chatType === 'all'){ // 群聊
    	$('a#returnBack').attr('href', '#/home');
		var data = {
			obj: [{
				account: '2323442',
				icon: '',
				user_name: 'Bella'
			}],
			attributes: {
				userName: 'Miya'
			}
		};
		$scope.familyList = data.obj;
		$scope.familyInfo = data.attributes;
		// 前端存储家属的用户名和头像
		data_sessionStorage.familyInfo.name = $scope.familyInfo.userName;
		data_sessionStorage.familyInfo.icon = $scope.familyInfo.icon;
		data_sessionStorage.familyInfo.sex = $scope.familyInfo.sex;
		sessionStorage.setItem('data_sessionStorage', JSON.stringify(data_sessionStorage));
		
		// 未绑定 给出提示 跳转到绑定页面
		if (data.obj.length == 0) {
			$.dialog.showDialog({
				msgTxt : '您还没有绑定，现在去绑定一位就可以与他们互动了~',
				isShowBtnCancel : false,
				callbackOk : function () {
					// 记录从哪个页面跳转到绑定页面
			    	data_sessionStorage = JSON.parse(sessionStorage.getItem('data_sessionStorage'));
			    	data_sessionStorage.record_page.page_bind.from = '/addmessage';
			    	sessionStorage.setItem('data_sessionStorage', JSON.stringify(data_sessionStorage));
			    	
					$location.path('/bind');
					$scope.$apply();
				}
			});
		} else {
			// 有几位绑定的
            for (var i = 0; i < data.obj.length; i++) {
                push_touser += "_" + data.obj[i].hospitalId + "_";
                push_phone += "_" + data.obj[i].mobile + "_";
                push_name += "_" + data.obj[i].name + "_";
                push_card += "_" + data.obj[i].idCardNo + "_";
                
                olderlist += (olderlist == "" ? data.obj[i].hospitalId : "," + data.obj[i].hospitalId);
            }
		}
	} else {
    	$.dialog.showDialog({
			msgTxt : '未知异常了 T_T',
			isShowBtnCancel : false,
			callbackOk : function () {
				window.location.replace(basepath + 'login.html');
				return;
			}
		});
    }
	
	/**
	 * 显示发送照片/视频
	 */
	$scope.slideImgSend = function() {
        if ($('#imgSendWrap').is(':visible')) {
            $('#imgSendWrap').hide();
            $('#imgSendWrap').animate({
                height: 0
            }, 100);
            $('.chat-wrap').css('margin-bottom', 50 + 'px');
        } else {
            $('#imgSendWrap').show();
            $('#imgSendWrap').animate({
                height: 120
            }, 150);
            $('.chat-wrap').css('margin-bottom', 50 + 120 + 'px');
            // 页面滚动至最底部
            $('body').animate({
            	scrollTop : $('body').height() + 100
            }, 200);
        }
    };
    
    /**
     * 发送 按钮 发送文字消息
     */
    var appElement = document.querySelector('[ng-controller=controller_familyapp]');
    var loadingScope = angular.element(appElement).scope();
    $scope.sendMsg = function () {
    	// 加遮罩
    	loadingScope.loading = true;
        loadingScope.$apply();
    	
    	$scope.isSendImg = false;
    	$('body').animate({
        	scrollTop : $('body').height()
        }, 200);
    	
        $scope.save();
    };
    
    /**
	 * 获取当前年月日
	 */
    $scope.getDate = function() {
        var d = new Date();
        var str = '', m = '', da = '', h = '', i = '';
        
        if (d.getMonth() + 1 < 10) {
        	m = '0' + (d.getMonth() + 1);
        } else {
        	m = d.getMonth() + 1;
        }
        
        if (d.getDate() < 10) {
        	da = '0' + d.getDate();
        } else {
        	da = d.getDate();
        }
        
        if (d.getHours() < 10) {
        	h = '0' + d.getHours();
        } else {
        	h = d.getHours();
        }
        
        if (d.getMinutes() < 10) {
        	i = '0' + d.getMinutes();
        } else {
        	i = d.getMinutes();
        }

        str += d.getFullYear() + '-' + m + '-' + da + ' ' + h + ':' + i;

        return str;
    };
    
    /**
	 * 选完照片上传至服务器
	 */
    $scope.sendImg = function() {
        $scope.isSendImg = true;
        // 聊天内容部分滚动至底部
        $('body').animate({
        	scrollTop : $('body').height()
        }, 200);
        $('#imgSendWrap').css({
        	'display' : 'none',
        	'height' : 0
        });
        
        $scope.save();
    };

    /**
     * 将发送的内容上传至服务器
     */
    $scope.save = function() {
        var videoErrorMsg = true;
        
        if (!$scope.isSendImg) { // 发送的是文字
        	if ($scope.msgCont == '') {
        		$.dialog.showToast({msgTxt : '写点什么吧。'});
            	return;
        	}
        	
        	$scope.obj.push_content = $scope.msgCont;
			// 获得类型
			$scope.obj.push_type = "PUSH_TYPE_WORD";
			$scope.obj.push_url = "";
			$scope.obj.push_img = "";
			
			// 显示图片loading的效果
        	$scope.isSending = true;
        	$scope.msgList.push({
        		isSending : true,
        		push_type: 'PUSH_TYPE_WORD',
        		push_time: '发送中',
        		push_content: '',
        		icon : $scope.familyInfo.icon,
        		sex : $scope.familyInfo.sex,
        		push_from : $scope.familyInfo.userName,
                flag : '0' // 0-发送 1-回复 
        	});
        } else { // 发送的是图片
        	var push_url = document.getElementById('sendImg').value; // 用户选择的图片
            videoErrorMsg = validateFile(push_url);
            
        	if (videoErrorMsg) {
                $scope.obj.push_content = "";
                // 获得类型
                $scope.obj.push_type = validatetype(push_url);
                // 获得图片地址
                var imgurl = validateUrl(push_url);
                $scope.obj.push_url = imgurl.split(",")[0];
                $scope.obj.push_img = imgurl.split(",")[0];
            }
        	
        	// 显示图片loading的效果
        	$scope.isSending = true;
        	$scope.msgList.push({
        		isSending : true,
        		userType : 'Family',
        		push_type: $scope.obj.push_type,
        		push_time: '发送中',
                push_content: '../resources/images/i21.png',
        		icon : $scope.familyInfo.icon,
        		sex : $scope.familyInfo.sex,
        		push_from : $scope.familyInfo.userName,
                flag : '0' // 0-发送 1-回复 
        	});
        	$scope.$apply();
        	loaderShow();
        }

        // 验证文件格式是否是视频、音频、图片
        if (videoErrorMsg) {
            $scope.obj.push_touser = push_touser;
            $scope.obj.push_card = push_card;
            $scope.obj.push_phone = push_phone;
            $scope.obj.push_name = push_name;

            $scope.obj.push_touser = $scope.obj.push_touser.substring(1);
            $scope.obj.push_card = $scope.obj.push_card.substring(1);
            $scope.obj.push_phone = $scope.obj.push_phone.substring(1);
            $scope.obj.push_name = $scope.obj.push_name.substring(1);

            $scope.obj.push_touser = $scope.obj.push_touser.replace(/\__/g, "_");
            $scope.obj.push_card = $scope.obj.push_card.replace(/\__/g, "_");
            $scope.obj.push_phone = $scope.obj.push_phone.replace(/\__/g, "_");
            $scope.obj.push_name = $scope.obj.push_name.replace(/\__/g, "_");

            saveUpload($scope.obj, ["sendImg"], function (data) {
            	if (data.success) {
            		window.setTimeout(function () {
            			$scope.showcontent();
            		}, 1000);
            	} else {
            		window.setTimeout(function () {
            			// 隐藏遮罩
            	        loadingScope.loading = false;
            	        loadingScope.$apply();
            	        
	        			$.dialog.showToast({
	        				msgTxt : data.msg,
	        			}, function () {
	        				$scope.isSending = false;
	                    	$scope.msgList.pop();
	                    	$scope.$apply();
	        			});
	            	}, 1000);
            	}
            }, function (data) {
            	$scope.isSending = false;
            	$scope.msgList.pop();
            	$scope.$apply();
            	
            	$.dialog.showToast({msgTxt : '发送失败'});
            });
        } else {
        	$scope.isSending = false;
        	$scope.msgList.pop();
        	$scope.$apply();
        }
    };
   
    $scope.showcontent = function() {
    	$scope.isSending = false;
    	$scope.msgList.pop();
        // 页面展示
        $scope.obj.push_content = "";
        // 获得资源路径
        var url = $scope.obj.push_url;
        // 获得图片路径
        var videoImageUrl = imagebasepath + $scope.obj.push_img;
        
        // 根绝不同发送类别前台显示不同图片
        var contStr = '';
        if (!$scope.isSendImg) {
        	contStr = $scope.msgCont;
    	} else {
    		if ($scope.obj.push_type == 'PUSH_TYPE_IMAGE') { // 图片
    			contStr = url;
    		} else { // 视频
    			contStr = returnTypeImg($scope.obj.push_type);
    		}
    	} 
        
        $scope.msgList.push({
        	isSending : false,
        	userType : 'Family',
            push_type: $scope.obj.push_type,
            push_time: $scope.getDate(),
            push_content : contStr,
            push_img : contStr,
    		icon : $scope.familyInfo.icon,
    		sex : $scope.familyInfo.sex,
    		push_from : $scope.familyInfo.userName,
            flag : '0' // 0-发送 1-回复 
        });
        
        // 文本框清空
        $scope.msgCont = '';
        $scope.$apply();
        
        // 聊天内容部分滚动至底部
        $('body').animate({
        	scrollTop : $('body').height()
        }, 200);
        $('#imgSendWrap').css({
        	'display' : 'none',
        	'height' : 0
        });
        $('.chat-wrap').css('margin-bottom', 50 + 'px');
        
        // 隐藏遮罩
        loadingScope.loading = false;
        loadingScope.$apply();
    };
    
    /**
     * 点击页面空白处 
     * 隐藏发送图片/视频的区域
     */
    $(document).on("click",function(e){  
    	var target  = $(e.target);    // e.target获取触发事件的元素
    	if(target.closest("#chatFooter, #olderListWrap, .wechat-header").length == 0){
    		$('#imgSendWrap').hide();
    		$('.chat-wrap').css('margin-bottom', 50 + 'px');
    	}
    });
    
    /**
     * 判断上传的文件
     */
    function validateFile(fileName) {
    	var fileType = fileName.substring(fileName.lastIndexOf("."),fileName.length);
    	fileType = fileType.toLowerCase();
    	// .mov格式  苹果手机的视频格式
    	if(fileType.toLowerCase() != ".amr" && 
    		fileType.toLowerCase() != ".mp3" && 
    		fileType.toLowerCase() != ".jpg" && 
    		fileType.toLowerCase() != ".png" &&
    		fileType.toLowerCase() != ".jpeg" &&
    		fileType.toLowerCase() != ".mp4" && 
    		fileType.toLowerCase() != ".mov"){
    		$.dialog.showToast({msgTxt : '文件格式不支持，请重新上传。'});
    		return false;
    	}
    	
    	// 判断上传的文件大小 单位M
    	var fileSize = document.getElementById('sendImg').files[0].size / 1024 / 1024; 
    	if (fileSize > chatfileSize) {
    		$.dialog.showToast({msgTxt : '文件不可以超过10M哦。'});
    		return false;
    	}
    	
    	return true;
    }
    
    /**
     * 获得类型code
     * @param fileName
     */
    function validatetype(fileName) {
    	var fileType = fileName.substring(fileName.lastIndexOf("."),fileName.length);
    	fileType = fileType.toLowerCase();
    	var type = "";
    	// 语音
    	if(fileType == ".amr" || 	fileType== ".mp3"){
    		type = "PUSH_TYPE_SOUND";
    	} else if(fileType == ".jpg" ||  fileType == ".png" || fileType == ".jpeg"){
    		type = "PUSH_TYPE_IMAGE"
    	} else {
    		type = "PUSH_TYPE_VIDEO";
    	}
    	return type;
    }
    
    /**
     * 获得地址
     * @param fileName
     */
    function validateUrl(fileName) {
    	var fileType = fileName.substring(fileName.lastIndexOf("."),fileName.length);
    	fileType = fileType.toLowerCase();
    	// 语音
    	if(fileType == ".amr" || 	fileType== ".mp3"){
    		url = "upload/lovesound/" + uuid() + fileType;
    	} else if(fileType == ".jpg" ||  fileType == ".png" || fileType == ".jpeg"){
    		// 获得图片的地址
    		url = "upload/loveimage/" + uuid() + fileType;
    	} else {
    		url = "upload/lovevideo/" + uuid() + fileType;
    		url = url + ",upload/lovevideo/" + uuid() + ".png";
    	}
    	return url;
    }
    
    function uuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "";
     
        var uuid = s.join("");
        return uuid;
    }
    
    /**
     * 图片上传过程中的进度条
     */
    function loaderShow () {
    	$('#loaded').animate({
    		width : '80%'
    	}, 1500);
    }
    
    /**
     * 根据发送类型展示相应图片
     */
    function returnTypeImg (type) {
    	var str = '';
    	if (type == 'PUSH_TYPE_SOUND') { // 语音
    		str = '../resources/images/play_3.png';
    	} else if (type == 'PUSH_TYPE_VIDEO') { // 视频
    		str = '../resources/images/video_icon.png';
    	}
    	return str;
    }
    
    /**
     * 上传文件专用保存
     * @param item
     * @param url
     * @param fileArray
     * @param funSuccess
     */
    function saveUpload(item, fileArray, funSuccess, funcError) {
    	// 地址
    	var postUrl = basepath + "interactionController/sendInfo.htm";
    	// 显示加载dialog
    	var objString = JSON.stringify(item).replace(/\"/g, "'");
    	$.ajaxFileUpload({
    		url : postUrl,
    		secureuri : false,
    		fileElementId : fileArray,
    		type : 'POST',
    		dataType : "json",
    		data : {"obj" : objString},
    		success : funSuccess,
    		error : funcError
    	});
    }
    
    /**
     * 点击 跳至个人信息页面
     * @param hospitalId account
     */
    $scope.toSelfInfo = function (hospitalId) {
    	data_sessionStorage = JSON.parse(sessionStorage.getItem('data_sessionStorage'));
    	data_sessionStorage.chat.olderTarget_account = hospitalId;
    	sessionStorage.setItem('data_sessionStorage', JSON.stringify(data_sessionStorage));
    	$location.path('/olderinfo');
    	$scope.$apply();
    };
    
    /**
     * 去绑定
     */
    $scope.gotoBind = function () {
    	// 记录从哪个页面跳转到绑定页面
    	data_sessionStorage = JSON.parse(sessionStorage.getItem('data_sessionStorage'));
    	data_sessionStorage.record_page.page_bind.from = '/addmessage';
    	sessionStorage.setItem('data_sessionStorage', JSON.stringify(data_sessionStorage));
    	
    	$location.path('/bind');
    	$scope.$apply();
    };
    
    /**
     * 发送文本的输入框 激活状态 页面自动到最底部 
     * 解决个别输入法挡住输入框的问题
     */
	$scope.autoBottom = function (obj) {
    	$('body').animate({
        	scrollTop : $('body').height() + 100
        }, 200);
    	// 解决输入法打开有延迟的情况
    	setTimeout(function () {
    		$('body').animate({
    	    	scrollTop : $('body').height() + 100
    	    }, 200);
    	}, 600);
	};
    
});